package com.persicadev.khayyam;

import java.util.Calendar;
import java.util.Random;

import com.persicadev.khayyam.R;
import com.persicadev.khayyam.IPoemDb.Poem;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.Bitmap.Config;
import android.graphics.Paint.Align;
import android.graphics.Canvas;
import android.widget.RemoteViews;

public class KhayyamWidget extends AppWidgetProvider {

	public static final String PREFS_WIDGET = "com.persicadev.khayyam.widget";
	public static final String KEY_PERIOD = "period";
	public static final String KEY_IDS = "ids";
	
	private boolean hasPersian = false;
	private RemoteViews remoteViews = new RemoteViews("com.persicadev.khayyam", R.layout.khayyamwidget);
	private SharedPreferences mSharedPreferences;
	
	private String a(String s) {
		char chars[] = s.toCharArray();
		char re[] = new char[chars.length];
		for (int i=0; i<re.length; i++) {
			re[i] = chars[re.length-i-1];
		}
		return new String(re);
	}

	private Bitmap drawPoem(Poem poem, Context context) {
		poem.getVerse(0).setPart1(PersianReshape.reshape(poem.getVerse(0).getPart1()));
		poem.getVerse(0).setPart2(PersianReshape.reshape(poem.getVerse(0).getPart2()));
		poem.getVerse(1).setPart1(PersianReshape.reshape(poem.getVerse(1).getPart1()));
		poem.getVerse(1).setPart2(PersianReshape.reshape(poem.getVerse(1).getPart2()));
		if (!hasPersian) {
			poem.getVerse(0).setPart1(a(poem.getVerse(0).getPart1()));
			poem.getVerse(0).setPart2(a(poem.getVerse(0).getPart2()));
			poem.getVerse(1).setPart1(a(poem.getVerse(1).getPart1()));
			poem.getVerse(1).setPart2(a(poem.getVerse(1).getPart2()));
		}
		Bitmap bitmap = Bitmap.createBitmap(400, 100, Config.ARGB_8888);
		Canvas canvas = new Canvas(bitmap);
		Paint mPaint = new Paint();
		mPaint.setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/BZar.ttf"));
		mPaint.setTextSize(((float)canvas.getWidth())/18);
		mPaint.setColor(0xff000000); // aa0055 a54921
		float top = -mPaint.ascent()*7/8;
		float line = mPaint.getFontSpacing()/5-mPaint.ascent()+mPaint.descent();
		float space = context.getResources().getDisplayMetrics().widthPixels/25;
		mPaint.setTextAlign(Align.RIGHT);
		canvas.drawText(poem.getVerse(0).getPart1(), canvas.getWidth()-space, top, mPaint);
		mPaint.setTextAlign(Align.LEFT);
		canvas.drawText(poem.getVerse(0).getPart2(), space, top+line, mPaint);
		mPaint.setTextAlign(Align.RIGHT);
		canvas.drawText(poem.getVerse(1).getPart1(), canvas.getWidth()-space, top+2*line, mPaint);
		mPaint.setTextAlign(Align.LEFT);
		canvas.drawText(poem.getVerse(1).getPart2(), space, top+3*line, mPaint);
		return bitmap;
	}
	
	private void prepareRemoteView(Context context) {
		hasPersian = RobaeiView.hasPersian(context);
		
		IPoemDb poemDb = new PoemEngine(context);
		Poem poem = null;
		if (mSharedPreferences.contains(KEY_IDS)) {
			String ids[] = mSharedPreferences.getString(KEY_IDS, "").split(",");
			poem = poemDb.getPoem(Integer.valueOf(ids[new Random().nextInt(ids.length)]));
		}
		else {
			poem = poemDb.getPoem(new Random().nextInt(poemDb.totalPoems()));
		}
		
		remoteViews.setImageViewBitmap(R.id.widget_image, drawPoem(poem, context));
    	Intent intent = new Intent("com.persicadev.khayyam.updatewidget");
    	PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
		remoteViews.setOnClickPendingIntent(R.id.widget_image, sender);
	}
	
	public static void setAlarm(SharedPreferences sp, Context context) {
        int period = sp.getInt(KEY_PERIOD, 0);
        if (period!=0) {
        	Intent intent = new Intent("com.persicadev.khayyam.updatewidget");
        	PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
        	Calendar calendar = Calendar.getInstance();
        	calendar.setTimeInMillis(System.currentTimeMillis());
        	calendar.add(Calendar.MILLISECOND, period);
        	AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        	am.set(AlarmManager.RTC, calendar.getTimeInMillis(), sender);
        }
	}
	
	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {
		if (mSharedPreferences==null) mSharedPreferences = context.getSharedPreferences(PREFS_WIDGET, Context.MODE_PRIVATE);
		prepareRemoteView(context);
		appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
		setAlarm(mSharedPreferences, context);
		super.onUpdate(context, appWidgetManager, appWidgetIds);
	}
	
	@Override
	public void onReceive(Context context, Intent intent) {
		super.onReceive(context, intent);
		if (mSharedPreferences==null) mSharedPreferences = context.getSharedPreferences(PREFS_WIDGET, Context.MODE_PRIVATE);
		ComponentName cn = new ComponentName(context, KhayyamWidget.class);
		prepareRemoteView(context);
		AppWidgetManager.getInstance(context).updateAppWidget(cn, remoteViews);
		setAlarm(mSharedPreferences, context);
	}

}
